#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
#=============================================================================
#     FileName: admin.py
#         Desc: Manage the blog
#       Author: cold night
#        Email: wh_linux@126.com
#     HomePage: http://www.linuxzen.com/
#      Version: 0.0.1
#   LastChange: 2012-06-12 13:16:54
#      History:
#=============================================================================
'''

import re
from bottle import template, request, response
from bottle import route
from bottle import redirect
from model import model
from setting import TEMPLATE
from model.auth import blog_auth


TEMPLATE['BLOG_NAME'] = model.get_option('BLOG_NAME')
TEMPLATE['SUBTITLE'] = model.get_option('SUBTITLE')
TEMPLATE['ADMINMAIL'] = model.get_option('ADMINMAIL')

#===============================================================================
# 后台首页
#===============================================================================
@route('/admin:#/?#')
@blog_auth
def admin():
    '''
    用于显示后台管理首页
    用此方法检查用户,所有管理页面都是在admin的子连接中如果url为真且
    用户验证没有问题则重定向到执行页面否则则重定向到首页
    '''
    TEMPLATE['title'] = u'仪表盘 | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE['user'] = request.COOKIES.get('user', '')

    # 将文章列表交给前台模版
    TEMPLATE['articles'], conunt = model.get_articles()
    return template('admin.html',TEMPLATE)

#===============================================================================
# 写文章
#===============================================================================
#创建一个在线编辑器
@route('/admin/write:#/?#')
@blog_auth
def write():
    '''
    创建一个编辑页面用于写文章
    '''
    # 获取分类目录交给前台模板
    categories = model.get_categories()

    # 关闭编辑模式    
    TEMPLATE['edit'] = False

    # 关闭消息提醒
    TEMPLATE['info'] = False

    TEMPLATE['post_title'] = ''
    TEMPLATE['post_content'] = ''
    TEMPLATE['cids'] = ''
    TEMPLATE['tags'] = ''
    TEMPLATE['categories'] = categories
    TEMPLATE['title'] = u'写文章 | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE['user'] = request.COOKIES.get('user', '')
    return template('admin-write.html', TEMPLATE)


# 处理post提交的文章
@route('/admin/write/posts', method='POST')
@blog_auth
def write_post():
    '''
    处理post请求,将文章插入到数据库
    '''
    # 获取表单数据
    articles_data = request.POST

    # 获取类别
    cateids = []
    for key in articles_data.keys():
        if re.match(r'^cate-(?:[0-9a-f]{24}|\d+)',key):
            cateids.append(articles_data[key])

    title = articles_data['title']
    content = articles_data['content']
    tags = articles_data['tags'].split(',')
    artid = model.article_post(dict(title = title, content = content,
                            categories = cateids, tags = tags))
    redirect('/admin/articles/edit/'+str(artid))



# 列出所有文章
@route('/admin/articles')
@blog_auth
def articles_list():
    '''
    用于列出文章列表
    '''
    # 获取文章
    articles,count = model.get_articles()
    print articles
    TEMPLATE['title'] = u'所有文章 | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE['user'] = request.COOKIES.get('user', '')
    TEMPLATE['articles'] = articles

    return template('admin-article.html', TEMPLATE)


#编辑文章
@route('/admin/articles/edit/:id#(?:[0-9a-f]{24}|\d+)#')
@blog_auth
def articles_edit(id):
    '''
    编辑文章
    '''
    TEMPLATE['title'] = u'编辑文章  | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE['user'] = request.COOKIES.get('user', '')

    # 转换成数字
    artid = id


    article = model.get_articles(artid)
    print article
    #获取类别
    categories = model.get_categories()

    TEMPLATE['post_title'] = article['title']
    TEMPLATE['post_content'] = article['content']
    TEMPLATE['cids'] = [x.get('_id') for x in article.get('categories')]
    TEMPLATE['tags'] = ','.join(article['tags'])
    TEMPLATE['categories'] = categories
    TEMPLATE['edit'] = True
    TEMPLATE['artid'] = article['_id']

    return template('admin-write.html', TEMPLATE)


# 处理编辑后提交的数据
@route('/admin/write/edit/posts', method="POST")
@blog_auth
def article_edit_post():
    '''
    处理编辑文章后提交的数据
    '''

    # 获取表单数据
    articles_data = request.POST

    # 获取类别
    cateids = []
    for key in articles_data.keys():
        if re.match(r'^cate-(?:[0-9a-f]{24}|\d+)',key):
            cateids.append(articles_data[key])

    title = articles_data['title']
    content = articles_data['content']
    tags = articles_data['tags'].split(',')
    artid = articles_data['artid']
    # 判断各项内容是否为空
    if title == '' or content == '' or tags == '' or not cateids:
        TEMPLATE['info'] = "Error"
    else:
        result = model.article_edit(artid, dict(title = title,
                                         content = content,
                                         tags = tags,
                                         categories = cateids))
        TEMPLATE['info'] = 'Success'
        TEMPLATE['edit'] = True
        TEMPLATE['artid'] = artid
    redirect('/admin/articles/edit/'+artid)



# 删除文章处理
@route('/admin/articles/del/:id#(?:[0-9a-f]{24}|\d+)#')
@blog_auth
def article_del(id):
    '''
    处理文章删除请求
    '''
    model.article_del(id)

    redirect("/admin/articles")


@route('/admin/articles/bulkdel', method="POST")
@blog_auth
def bulkdel_arti():
    '''
    批量删除文章
    post数据包括:
          art-\d+ -> 文章id
          dropdown -> del 则删除否则不操作
    '''
    delpost = request.POST
    if delpost['dropdown'] == 'del':
        # 判断是执行删除操作则开始执行操作
        # 获取选中文章id
        # 初始化选中列表
        dellist = []
        for key in delpost.keys():
            if re.match(r'art-(?:[0-9a-f]{24}|\d+)', key):
                dellist.append(delpost[key])

        model.article_del(dellist)
        
        redirect('/admin/articles')

    


#==========================================================================
# 评论管理
#==========================================================================
@route('/admin/comments')
@blog_auth
def comments_list():
    '''
    管理评论:
        查询数据库,并在前端显示一个控制列表
    '''
    TEMPLATE['title'] = u'评论管理 | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE['user'] = request.COOKIES.get('user', '')
    
    TEMPLATE['comments'], TEMPLATE['pagecount'] = model.get_comments()
    return template('admin-comments.html', TEMPLATE)




@route('/admin/comments/del/cid/:cid#(?:[0-9a-f]{24}|\d+)#/')
@blog_auth
def del_comments(cid):
    '''
    用于删除评论
    提取一个url参数:
        cid -> 评论id
    '''
    model.comment_del(cid)
    redirect('/admin/comments')

@route('/admin/comments/bulkdel', method="POST")
@blog_auth
def bulkdel_comments():
    '''
    批量删除评论
    处理post请求
    post的数据为:
        comm-\d+  -> 评论id
        dropdown  -> 执行的动作(del)
    '''
    # 获取表单数据
    drop_post = request.POST

    if drop_post['dropdown'] == 'del':
        commids = []
        for key in drop_post.keys():
            if re.match(r'comm-\d+', key):
                commids.append(drop_post[key])

        if commids:
            model.comment_del(commids)

            redirect('/admin/comments')
        else:
            return '没有选中项目'
    else:
        return '选择一个操作'

